<!-- 我的 -->
<template>
	<view class="user-page-container">
		<!-- 顶部橙色栏 -->
		<view class="header-bar">
			<text class="header-title">我的</text>
		</view>
		<!-- 登录按钮/用户名 -->
		<view class="login-section">
			<view v-if="!isLogin" class="user-info">
				<image class="avatar" src="/static/img/icon/icon_captain.png" mode="aspectFill"></image>
				<view class="user-detail">
					<text class="welcome">欢迎来到在线学习平台</text>
					<button class="login-btn" @click="showLoginPopup">立即登录</button>
				</view>
			</view>
			<view v-else class="user-info">
				<image class="avatar" :src="userinfo.avatar || '/static/img/icon/icon_captain.png'" mode="aspectFill">
				</image>
				<view class="user-detail">
					<view class="welcome-text">
						<text class="welcome">欢迎您，</text>
						<text class="username">{{ userName }}</text>
					</view>
					<view class="user-role" v-if="userinfo.roleName">
						<text class="role-tag">{{ userinfo.roleName }}</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 功能列表 -->
		<view class="list-section">
			<view class="list-item" @click="navTo('/pages/user/courses')">
				<text>我的课程</text>
				<text class="arrow">></text>
			</view>
			<view class="list-item" @click="navTo('/pages/notice/notice')">
				<text>通知公告</text>
				<text class="arrow">></text>
			</view>
			<!-- <view class="list-item" @click="navTo('/pages/user/pwdchange')">
				<text>修改密码</text>
				<text class="arrow">></text>
			</view> -->
			<view v-if="isLogin" class="list-item logout-item" @click="handleLogout">
				<text>退出登录</text>
				<text class="arrow">></text>
			</view>
		</view>
		<!-- 可选：底部背景格子 -->
		<view class="bg-grid"></view>

		<!-- 登录弹窗 -->
		<uni-popup ref="loginPopup" type="center">
			<view class="login-popup">
				<view class="popup-title">用户登录</view>
				<view class="input-group">
					<input type="text" v-model="loginForm.username" placeholder="请输入账号" />
					<input type="password" v-model="loginForm.password" placeholder="请输入密码" />
				</view>
				<view class="popup-buttons">
					<button class="cancel-btn" @click="closeLoginPopup">取消</button>
					<button class="confirm-btn" @click="handleLogin">确认</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		Platform,
		Storage_Key,
		UserJobsType,
		UserJobMenuAuth,
		timeslot,
	} from '@/static/config.js'
	import {
		GetAuthModule,
		GetUserJobKeys,
	} from '@/common/util.js'
	import request from '@/common/request.js';
	import BookingCarType from "@/pages/booking/components/booking-car/booking-car-type.vue"

	let startY = 0,
		moveY = 0,
		pageAtTop = true;
	export default {
		components: {
			BookingCarType
		},
		data() {
			return {
				platform_name: Platform.name,
				coverTransform: 'translateY(0px)',
				coverTransition: '0s',
				moving: false,
				// 授权字段
				Code: '',
				openid: '',
				session_key: '',
				// 用户相关状态
				wxUserInfo: {}, // 用户微信账号信息
				// usertypeindex: 0, // 用户类型序号，默认第0个，游客
				webUserInfo: {}, // 平台用户账号信息

				// 统计数据
				total_role1: {},
				total_role2: {

				},
				total_count: 0, // 默认值 

				listData1: [], // 权限模块数据
				listData2: [], // 权限模块数据
				isLogin: false,
				userName: '',

				// 登录表单
				loginForm: {
					username: '',
					password: '',
					code: "54",
					uuid: "45"
				},
				// 课程列表数据
				courseList: [],
				userinfo: {},
			}
		},
		onLoad() {
			this.init(); // 初始数据
			this.setListening(); // 设置监听
			this.refreshAuthModule(); // 刷新角色权限模块
		},
		onShow() {
			this.init()
		},
		// #ifndef MP
		onNavigationBarButtonTap(e) {
			const index = e.index;
		},
		// #endif
		computed: {},
		methods: {
			// 初始数据
			init() {
				let userinfo = this.$storage.get('userinfo', true);
				if (userinfo) {
					this.isLogin = true;
					this.userName = userinfo.userName
					this.userinfo = userinfo;
				} else {
					this.isLogin = false;
					this.userinfo = {}
				}
			},
			// 设置监听
			setListening() {
				let _self = this;
				uni.$on('RefreshUser', function(data) {
					if (data.key) {
						// 刷新角色权限模块
						_self.refreshAuthModule();
						_self.webUserInfo = data.msg;
						console.log(data.msg)
					}
				})
				uni.$on('exitUser', function(data) {
					if (data.key) {
						_self.doExit();
						console.log(data.msg)
					}
				})
			},
			// 刷新角色权限模块
			refreshAuthModule() {
				// 刷新首页权限菜单
				uni.$emit("RefreshIndexTabs", {
					key: true,
					// msg: webUserInfo
				})
				// 刷新我的权限菜单
				let authModuleData = GetAuthModule();
				this.listData1 = GetAuthModule('user-1');
				this.listData2 = GetAuthModule('user-2');
			},
			// 退出当前用户
			doExit() {
				// 清除本页平台用户账号信息
				this.webUserInfo = '';
				// 清除本地存储平台用户信息
				this.$storage.set(Storage_Key
					.web_user_info,
					'',
					true
				);
				// 清楚统计数据
				this.total_role1 = {};
				this.total_role2 = {};

				// 刷新角色权限模块
				this.refreshAuthModule();
			},
			// 显示登录弹窗
			showLoginPopup() {
				this.$refs.loginPopup.open();
			},

			// 关闭登录弹窗
			closeLoginPopup() {
				this.$refs.loginPopup.close();
				// 清空表单
				this.loginForm = {
					username: '',
					password: '',
					code: "54",
					uuid: "45"
				};
			},

			// 处理登录
			handleLogin() {
				if (!this.loginForm.username || !this.loginForm.password) {
					uni.showToast({
						title: '请输入账号和密码',
						icon: 'none'
					});
					return;
				}

				// 模拟登录请求
				uni.showLoading({
					title: '登录中...'
				});

				// 模拟后台登录验证
				request({
					url: Platform.api_requestUrl + '/login',
					method: 'POST',
					data: this.loginForm,
					Headers: {
						istoken: false
					}
				}).then(response => {
					if (response.code == 200) {
						// 模拟登录成功
						const userInfo = {
							userName: this.loginForm.username,
							nickName: this.loginForm.username,
							token: response.token
							// 可以添加更多用户信息
						};

						// 存储用户信息到全局Storage
						this.$storage.set('userinfo', userInfo, true);
						uni.setStorageSync('token', response.token)

						// 获取人员信息并获取课程列表
						this.getUserInfo();

						// 更新页面状态
						this.isLogin = true;
						this.userName = userInfo.userName;

						// 关闭弹窗
						this.closeLoginPopup();

						uni.hideLoading();
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});

					} else {
						uni.hideLoading();
						uni.showToast({
							title: '登录失败',
							icon: 'error'
						});
					}
					this.closeLoginPopup();
				}).catch(error => {
					this.messageToggle('error', '登录失败');
				});

			},
			// 
			// 处理退出登录
			handleLogout() {
				uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							// 清除用户信息
							this.$storage.set('userinfo', '', true);
							uni.removeStorageSync('token');
							// 更新页面状态
							this.isLogin = false;
							this.userName = '';
							// 触发退出事件
							uni.$emit('exitUser', {
								key: true,
								msg: '用户已退出'
							});
							uni.showToast({
								title: '已退出登录',
								icon: 'success'
							});
						}
					}
				});
			},
			// 获取统计数据
			getMyDynamicData() {
				this.getManageStat();
				this.getWorkStat();

			},
			// 获取统计数据 - 管理人员
			getManageStat() {
				this.total_role1 = {};
				this.total_role2 = {}
				let _self = this;
				request({
					url: Platform.api_requestUrl + '/stp-count/countToday',
					// data: {
					// 	//teamid: _self.webUserInfo.ownerid,
					// },
					method: 'GET',
				}).then(response => {
					if (!!response.data) {
						_self.total_role1 = response.data;
						_self.total_role2 = response.data;
					}
				}).catch(error => {
					console.log("获取车辆统计数据失败")
				});
			},
			// 获取统计数据 - 执行人员
			getWorkStat() {
				let _self = this;

			},
			navTo(item, istab) {
				if (item.indexOf('courses') > -1) {
					let token = uni.getStorageSync('token');
					if(!token){
						this.messageToggle('error', '请登录后查看!')
						return;
					}
				}
				uni.navigateTo({
					url: item
				});
			},
			showPopup() {
				this.$refs.bookingtypeDialog.open()
			},
			closeBookingtypeDialog() {
				this.$refs.bookingtypeDialog.close();
			},
			/**
			 *  卡片下拉和回弹
			 *  1.关闭bounce避免ios端下拉冲突
			 *  2.由于touchmove事件的缺陷（以前做小程序就遇到，比如20跳到40，h5反而好很多），下拉的时候会有掉帧的感觉
			 *    transition设置0.1秒延迟，让css来过渡这段空窗期
			 *  3.回弹效果可修改曲线值来调整效果，推荐一个好用的bezier生成工具 http://cubic-bezier.com/
			 */
			coverTouchstart(e) {
				if (pageAtTop === false) {
					return;
				}
				this.coverTransition = 'transform .1s linear';
				startY = e.touches[0].clientY;
			},
			coverTouchmove(e) {
				moveY = e.touches[0].clientY;
				let moveDistance = moveY - startY;
				if (moveDistance < 0) {
					this.moving = false;
					return;
				}
				this.moving = true;
				if (moveDistance >= 80 && moveDistance < 100) {
					moveDistance = 80;
				}
				if (moveDistance > 0 && moveDistance <= 80) {
					this.coverTransform = `translateY(${moveDistance}px)`;
				}
			},
			coverTouchend() {
				if (this.moving === false) {
					return;
				}
				this.moving = false;
				this.coverTransition = 'transform 0.3s cubic-bezier(.21,1.93,.53,.64)';
				this.coverTransform = 'translateY(0px)';
			},
			//
			getUserInfo() {
				let _self = this;
				request({
					url: Platform.api_requestUrl + '/getInfo',
					method: 'GET',
					headers: {
						'token': uni.getStorageSync('token')
					}
				}).then(response => {
					if (response.code === 200) {
						// 存储到全局变量
						this.$storage.set('permissions', response.data, true);
						this.$storage.set('roles', response.roles, true);
						this.$storage.set('permissions', response.data, true);
						if (response.user?.avatar) {
							response.user.avatar = Platform.api_requestUrl + '/' + response.user.avatar
						}
						_self.userinfo = response.user;
						this.$storage.set('userinfo', Object.assign(this.loginForm, response.user), true);
						// 触发全局事件，通知其他组件课程列表已更新
						uni.$emit('courseListUpdated', {
							key: true,
							data: response.data
						});
						this.getCourseList();
						uni.hideLoading();
					} else {
						uni.hideLoading();
						uni.showToast({
							title: response.msg || '获取课程列表失败',
							icon: 'none'
						});
					}
				}).catch(error => {
					uni.hideLoading();
					uni.showToast({
						title: '获取课程列表失败',
						icon: 'none'
					});
				});
			},
			// 获取课程列表
			getCourseList() {
				if (!this.isLogin) {
					return;
				}

				uni.showLoading({
					title: '加载中...'
				});

				request({
					url: Platform.api_requestUrl + '/treatment/course_user_permisson/list',
					method: 'GET',
					data: {
						userId: this.userinfo?.userId || '',
						status: 'Y'
					},
					headers: {
						'token': uni.getStorageSync('token')
					}
				}).then(response => {
					if (response.code === 200) {
						// 存储到全局变量
						this.$storage.set('courseList', response.rows.map(item => item.courseId), true);
						// 触发全局事件，通知其他组件课程列表已更新
						uni.$emit('courseListUpdated', {
							key: true,
							data: response.data
						});
						uni.hideLoading();
					} else {
						uni.hideLoading();
						uni.showToast({
							title: response.msg || '获取课程列表失败',
							icon: 'none'
						});
					}
				}).catch(error => {
					uni.hideLoading();
					uni.showToast({
						title: '获取课程列表失败',
						icon: 'none'
					});
				});
			},
		}
	}
</script>
<style lang='scss' scoped>
	/* scss知识点： 占位选择器 %foo 
	是sass提供的一种特殊选择器，以%开头。
	带有占位选择器的选择器只能被 @extend语句 引用，单独使用时不会被编译为原生css。
	
	scss知识点： 继承 @extend error类名
		给指定标签加error类名
	*/
	%flex-center {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	%section {
		display: flex;
		justify-content: space-around;
		align-content: center;
		background: #fff;
		border-radius: 10upx;
	}

	.user-page-container {
		min-height: 100vh;
		background: #fcfcfa;
		position: relative;
	}

	.header-bar {
		width: 100%;
		height: 60px;
		background: linear-gradient(to right, #f45a1c, #ff6b3d);
		color: #fff;
		font-size: 22px;
		text-align: center;
		line-height: 60px;
		font-weight: bold;
		position: relative;
		box-shadow: 0 2px 10px rgba(244, 90, 28, 0.2);
	}

	.header-title {
		position: relative;

		&::after {
			content: '';
			position: absolute;
			bottom: -5px;
			left: 50%;
			transform: translateX(-50%);
			width: 30px;
			height: 3px;
			background: #fff;
			border-radius: 2px;
		}
	}

	.login-section {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 140px;
		background: #fff;
		padding: 20px;
		margin-bottom: 15px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
	}

	.user-info {
		display: flex;
		align-items: center;
		width: 100%;
	}

	.avatar {
		width: 70px;
		height: 70px;
		border-radius: 50%;
		margin-right: 20px;
		border: 3px solid #f45a1c;
		box-shadow: 0 2px 10px rgba(244, 90, 28, 0.2);
		transition: transform 0.3s ease;

		&:active {
			transform: scale(0.95);
		}
	}

	.user-detail {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.welcome-text {
		display: flex;
		flex-direction: column;
		margin-bottom: 8px;
	}

	.welcome {
		font-size: 16px;
		color: #666;
		margin-bottom: 5px;
	}

	.username {
		font-size: 22px;
		color: #333;
		font-weight: bold;
	}

	.user-role {
		margin-top: 5px;
	}

	.role-tag {
		display: inline-block;
		padding: 4px 12px;
		background: rgba(244, 90, 28, 0.1);
		color: #f45a1c;
		border-radius: 15px;
		font-size: 14px;
	}

	.login-btn {
		width: 180px;
		height: 40px;
		background: linear-gradient(to right, #f45a1c, #ff6b3d);
		color: #fff;
		font-size: 18px;
		border-radius: 20px;
		border: none;
		margin-top: 10px;
		box-shadow: 0 2px 10px rgba(244, 90, 28, 0.2);
		transition: transform 0.3s ease;

		&:active {
			transform: scale(0.95);
		}
	}

	.list-section {
		margin: 15px;
		background: #fff;
		border-radius: 10px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
		overflow: hidden;
	}

	.list-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 18px 20px;
		font-size: 16px;
		color: #333;
		border-bottom: 1px solid #f0f0f0;
		transition: background-color 0.3s ease;

		&:active {
			background-color: #f9f9f9;
		}
	}

	.arrow {
		color: #bbb;
		font-size: 18px;
		transition: transform 0.3s ease;
	}

	.list-item:active .arrow {
		transform: translateX(3px);
	}

	.logout-item {
		margin-top: 20px;
		border-top: 10px solid #f5f5f5;

		text {
			color: #f45a1c;
		}

		.arrow {
			color: #f45a1c;
		}
	}

	.bg-grid {
		position: absolute;
		left: 0;
		right: 0;
		top: 220px;
		bottom: 0;
		background: repeating-linear-gradient(45deg, #fafaf8, #fafaf8 20px, #f5f5f3 20px, #f5f5f3 40px);
		z-index: -1;
		opacity: 0.5;
	}

	.login-popup {
		background-color: #fff;
		border-radius: 10px;
		padding: 20px;
		width: 280px;
	}

	.popup-title {
		font-size: 18px;
		font-weight: bold;
		text-align: center;
		margin-bottom: 20px;
	}

	.input-group {
		margin-bottom: 20px;

		input {
			width: 100%;
			height: 40px;
			border: 1px solid #ddd;
			border-radius: 4px;
			margin-bottom: 10px;
			padding: 0 10px;
			box-sizing: border-box;
		}
	}

	.popup-buttons {
		display: flex;
		justify-content: space-between;

		button {
			width: 45%;
			height: 36px;
			line-height: 36px;
			text-align: center;
			border-radius: 4px;
			font-size: 14px;
		}

		.cancel-btn {
			background-color: #f5f5f5;
			color: #666;
		}

		.confirm-btn {
			background-color: #f45a1c;
			color: #fff;
		}
	}
</style>